Leetcode 1. Two sum


Posted by a113062130630210 on 2022-05-18

Problem description

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Constraints

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

Testcases

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

My solution

It is easy to come up with an $O(n^2)$ solution, just iterate through every index, and for every index, iterate again, then one can get the answer

However, can we solve this problem using less than $O(n^2)$ time complexity?

The answer is yes.

First we will provide a $O(n \log n)$ time complexity solution

to be continue

Code

$O(n^2)$ solution:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> sol;
        bool flag = false;
        for(int i = 0 ; i < nums.size() ; i++){
            if(flag == true) break;
            for(int j = i + 1 ; j < nums.size() ; j++){
                if(nums[i] + nums[j] == target){
                    sol.push_back(i), sol.push_back(j);
                    flag = true;
                    break;
                }
            }
        }
        return sol; 
    }
};

$O(n\log n)$ solution:
to be continue


#Leetcode







Related Posts

Git中使用HTTPS和SSH協議的區別 與 如何設定

Git中使用HTTPS和SSH協議的區別 與 如何設定

Unlocking the Secrets: How to Farm Diablo 4 Gold and Rare Items Like a Pro

Unlocking the Secrets: How to Farm Diablo 4 Gold and Rare Items Like a Pro

滲透測試基本技術 第二章(中篇)

滲透測試基本技術 第二章(中篇)


Comments